<template>
	<om-addpage style="padding-top: 35px;" :menuList='menuList' :busCode="busCode" :menuName="menuName" @formSubmit="formSubmit" :showHistoryBtn="true" :showChooseBtn="ismenu">
		<om-autoform ref="autoform" :checkedit="checkedit" :initConfigData="mainConfigData" :initValue="initValue"></om-autoform>
		<om-white-space bgColor="#eee"></om-white-space>
	</om-addpage>
</template>

<script>
import { getUrl,confirmModal, ptFloat, minusF, addF, errorModal } from '@/static/js/common.js';
import { buildFormData, formValidation, tranferToEditors, changeEditor,setSubmitSubValue, configSelectData, hasValue,formShowLoading ,getFormFields,formModelLoad,getWorkCacheKey} from '@/static/js/formUtil.js';
import urlUtil from '@/static/js/urlUtil.js';
import { mapState } from 'pinia';
import {useLoginUserStore} from '@/stores/login-user.js';
import moment from '@/static/js/moment.js'
export default {
	provide() {
		return {
			formPage: this
		};
	},
	data() {
		return buildFormData({
			initValue: {
				paySum:"",
				dataStr:""
			},
			formdata: {
				paySum:"",
				reimbursementAmount:"",
				payAmount:"",
			},
			ismenu:false,
			menuList:[],
			userCacheKey:"fin-bx-travels-user-cache",
			currencyIdCacheKey:"fin-bx-travels-currencyId-cache",
			expenseCategoryIdCacheKey:"fin-bx-travels-expenseCategoryId-cache",
			bankUserIdCacheKey:"fin-bx-travels-bankUserId-cache",
			codeMap: {},
			dvid: '',
			partakeInstCache:'fin-bx-travels-partakeInst-cache',
			feesAggregatedWayCache:'fin-bx-travels-feesAggregatedWay-cache',
			partakeUserCache:'fin-bx-travels-partakeUser-cache',
			researchDevelopmentCache:'fin-bx-travels-researchDevelopment-cache',
			businessOpportunityCache:'fin-bx-travels-businessOpportunity-cache',
			saleOrderCache:'fin-bx-travels-saleOrder-cache',
			marketingPlanningProductCache:'fin-bx-travels-marketingPlanningProduct-cache',
			newProductCache:'fin-bx-travels-newProduct-cache',
			setDataCacheKey:'fin-bx-travels-setData-cache',
			setData:{
				partakeInstId:'',
				partakeInstName:'',
				feesAggregatedWayIds:'',
				feesAggregatedWayName:''
			}
		})
	},
	computed: {
		...mapState(useLoginUserStore,['userName', 'userId'])
	},
	watch:{
		'formdata.reimbursementAmount':function(newVal,oldVal){
			let _that = this;
			if(_that.$refs.autoform.formdata.loanAmount > 0){
				let subNum = minusF(newVal,_that.$refs.autoform.formdata.loanAmount)
				if(subNum > 0){
					_that.$refs.autoform.formdata.payAmount = subNum
				}
			}else{
				_that.$refs.autoform.formdata.payAmount = newVal
			}
		},
		'formdata.repaymentAmount':function(newVal,oldVal){
			let _that = this;
			if(newVal){
				_that.$refs.autoform.formdata.payAmount = ''
				let subNum = minusF(_that.$refs.autoform.formdata.loanAmount,_that.$refs.autoform.formdata.reimbursementAmount)
				if (Number(subNum) >= 0 && (Number(newVal) > Number(subNum))) {
					errorModal(_that, '提示信息', '退还金额不能大于(借款金额-报销金额)', () => {
						_that.$refs.autoform.formdata.repaymentAmount = ''
					})
				}
			}
		},
		'formdata.payAmount':function(newVal,oldVal){
			let _that = this;
			if(newVal){
				if (Number(newVal) > 0 && (Number(newVal) > Number(_that.$refs.autoform.formdata.reimbursementAmount))) {
					errorModal(_that, '提示信息', '实付金额不能大于报销金额', () => {
						_that.$refs.autoform.formdata.payAmount = ''
					})
				}
			}
			 _that.getCapitalPaySumFunc(newVal)
		},
	}, 
	methods: {
		onInputErpProjectBatches(value){
			let _that = this
			let formdata = _that.$refs.autoform.formdata
			if(_that.subEditorObj['title2']){
				let dataList = _that.subEditorObj['title2'].workList
				for(let index in dataList){
					dataList[index].erpProjectBatches = value
				}
				formdata.dataStr = JSON.stringify(dataList)
				if(_that.subEditorObj['title2']){
					_that.subEditorObj['title2'].workList = dataList
				}
				_that.om.toast('子表数据已更新')
			}
		},
		clearBusinessOpportunity(){
			let _that = this
			_that.$refs.autoform.clear("title1","businessOpportunityId")
			_that.$refs.autoform.clear("title1","businessOpportunityCode")
		},
		clearResearchDevelopment(){
			let _that = this
			_that.$refs.autoform.clear("title1","researchDevelopmentId")
			_that.$refs.autoform.clear("title1","researchDevelopmentCode")
		},
		onSelectPartakeInst(id){
			let _that = this
			_that.$refs.autoform.changeEditor("title1","partakeUserId",{
				"link":'../../public/search/search',
				"linkParam":{
					other:JSON.stringify({
						instId:id
					}),
					url:'orgInstPosUserOfficial/getUserListByInstPosId',
					initload:true,
					namefield:'username',
					cachename:_that.partakeUserCache
				}
			})
		},
		verifyPartakeUser(){
			let _that = this
			if(!_that.$refs.autoform.formdata.partakeInstId){
				let title1 = _that.$refs.autoform.getEditorTitle("title1")
				let title2 = _that.$refs.autoform.getEditorTitle("title1","partakeInstId")
				errorModal(_that,'提示信息',title1+'的'+title2+'需要优先完成编辑!',()=>{
					return false
				})
			}else{
				return true
			}
		},
		onSelectRefundLoan(item){
			let _that  = this
			if(item.code == '38402'){
				_that.$refs.autoform.changeEditor("title1","repaymentAmount","type",'numberbox') //退款金额
				_that.$refs.autoform.changeEditor("title1","repaymentAmount","prompt",'请输入') 
				_that.$refs.autoform.changeEditor("title1","repaymentAmount","precision",'2')
			    _that.$refs.autoform.changeEditor("title1","repaymentAmount","required",true)
			}else{
				_that.$refs.autoform.changeEditor("title1","repaymentAmount","type",'labelbox') //退款金额
				_that.$refs.autoform.clear("title1","repaymentAmount")
				_that.$refs.autoform.changeEditor("title1","repaymentAmount","required",false)
			}
		},
		getListByCode(){
			let _that = this
			_that.om.request(
				"dictZero/getListByCode",
				{
					code:38400
				}
			).then(res=>{
				_that.$refs.autoform.changeEditor("title1","refundLoanCode","type",'selectbox')
				_that.$refs.autoform.changeEditor("title1","refundLoanCode","onSelect",'onSelectRefundLoan')
				_that.$refs.autoform.changeEditor("title1","refundLoanCode","data",configSelectData(res,'code','dicname'))
			})
		},
		ontextPayeeBankAccount(item){
			let _that = this;
			if(item){
				var str = _that.fliterChinese(item);
				if (str != item) {
					_that.$refs.autoform.formdata.payeeBankAccount = str
				}
			}
		},
		fliterChinese(str) {
		    let temp = "";
		    for (let i = 0; i < str.length; i++)
		        if (str.charCodeAt(i) > 0 && str.charCodeAt(i) < 255)
		            temp += str.charAt(i);
		    return temp;
		},
		verifyUserPosFunc(){
			let _that = this;
			if(!_that.$refs.autoform.formdata.keyUserId || !_that.$refs.autoform.formdata.keyPostId || !_that.$refs.autoform.formdata.expenseCategoryId){
				return "请先选择报销人、岗位名称和费用类别"
			}
		},
		getBankInfoFunc(userId){
			let _that = this;
			if(_that.$refs.autoform.formdata.keyUserId && _that.$refs.autoform.formdata.payTypeId == _that.codeMap.payeeBankRequiredId){
				_that.om.request("temployee/getBankInfo", {
					userId: userId
				}).then(res=>{
					if (res.succeed) {
						_that.$refs.autoform.formdata.payeeBankName = res.value.salaryBank.dicname
						_that.$refs.autoform.formdata.payeeBankAccount = res.value.salaryCard
					}else{
						_that.$refs.autoform.clear("title1","payeeBankName")
						_that.$refs.autoform.clear("title1","payeeBankAccount")
					}
				})
			}
		},
		getCapitalPaySumFunc(payAmount){
			let _that = this;
			_that.om.request("travelExpensesForm/getCapitalPaySum", {
				paySum: payAmount
			}).then(res=>{
				if (res.succeed) {
					_that.$refs.autoform.formdata.payCapitalAmount = res.value
				}
			})
		},
		onSubChange(editor){
			let _that = this.$refs.autoform
			let that = this
			if(editor.workList.length) {
				if(!that.checkedit){
					_that.formdata.reimbursementAmount = this._.sum(editor.workList.map(e=>ptFloat(e.applyPayNum)))
					_that.formdata.repaymentAmount = ''
					let num = minusF(this._.sum(editor.workList.map(e=>ptFloat(e.applyPayNum))),that.formdata.loanAmount)
					if(num >= 0){
						_that.formdata.payAmount
					}
				}else{
					_that.formdata.reimbursementAmount = this._.sum(editor.workList.map(e=>ptFloat(e.sumCosts)))
					_that.formdata.repaymentAmount = ''
					let num =  minusF(this._.sum(editor.workList.map(e=>ptFloat(e.sumCosts))),that.formdata.loanAmount)
					if(num >= 0){
						_that.formdata.payAmount
					}
				}
				let startDate = ''
				let endDate = ''
				let timeStrList = []
				let timtList = []
				for(let i=0;i<editor.workList.length;i++){
					let startTimeVal = editor.workList[i].startTime
					if (startDate) {
						if (new Date(startTimeVal) < new Date(startDate)) {
					        startDate = startTimeVal
					    }
					}else {
					    startDate = startTimeVal
					}
					let endTimeVal = editor.workList[i].endTime
					if (endDate) {
						if (new Date(endTimeVal) > new Date(endDate)) {
					        endDate = endTimeVal
					    }
					}else {
					    endDate = endTimeVal
					}
					if (startTimeVal && endTimeVal) {
					    let timeStr = startTimeVal.toString() + endTimeVal.toString();
					    //未有重复时间数据,计算天数
					    if (!timeStrList.includes(timeStr)) {
					        timeStrList.push(timeStr)
							let obj = JSON.parse(JSON.stringify(editor.workList[i]));
							obj.planStartTime = obj.planStartTime ? obj.planStartTime + ':00' : obj.planStartTime
							obj.planEndTime = obj.planEndTime ? obj.planEndTime + ':00' : obj.planEndTime
							obj.startTime = obj.startTime ? obj.startTime + ':00' : obj.startTime
							obj.endTime = obj.endTime ? obj.endTime + ':00' : obj.endTime
					        timtList.push(obj)
					    }
					}
				}
				_that.formdata.startTime = startDate
				_that.formdata.endTime = endDate
				if (timtList.length > 0) {
				    _that.om.request("travelExpensesForm/getDays", {
				    	dataStr: JSON.stringify(timtList)
				    },'post').then(res=>{
				    	if (res.succeed) {
				    		_that.formdata.days = res.value
				    	}
				    })
				}
			} else {
				_that.formdata.reimbursementAmount = 0
			}
			// this.getCapitalPaySum()
		},
		getCapitalPaySum(){
			this.verifyBackSum()
			this.calcPaySum()
			let _that = this.$refs.autoform
			var payNum = _that.formdata.payNum
			if(payNum){
				_that.om.request("common/getCapitalNum", {
					moneyNum: payNum
				}).then(res=>{
					if (res.succeed) {
						_that.formdata.capitalPaySum = res.value
					}
				})
			}else{
				_that.formdata.capitalPaySum = ""
			}
			
		},
		//计算退还金额
		verifyBackSum(item) {
			if(item){
				if(minusF(ptFloat(_that.formdata.loanSum),ptFloat(_that.formdata.selfPaySum)) < ptFloat(diff)){
					this.$refs.autoform.formdata.backSum = 0
				}
			}
		},
		//计算实付金额
		calcPaySum(){
			let _that = this.$refs.autoform
			let diff = minusF(ptFloat(_that.formdata.planPaySum),ptFloat(_that.formdata.paySum))
			_that.formdata.payNum = diff<0?Math.abs(diff):''
		},
		formSubmit() {
			let _that = this;
			if(Number(_that.$refs.autoform.formdata.reimbursementAmount) == 0){
				let title = _that.$refs.autoform.getEditorTitle("title1","reimbursementAmount")
				confirmModal(_that,'提示信息',title+"为零，是否继续保存！",()=>{
					_that.om.request("travelExpenses/verifyLoanMoney1",_that.formdata,"post").then(res=>{
						if(res.succeed) {
							var obj = res.value;
							if(obj.msg){
								confirmModal(_that, '提示信息', obj.msg,()=>{
									if(obj.flag){
										_that.save()
									}
								},()=>{
									
								});
							}else if(obj.flag){
								_that.save()
							}
						}else{
							_that.om.toast(res.msg)
						}
					})
				},()=>{})
			}else{
				_that.om.request("travelExpenses/verifyLoanMoney1",_that.formdata,"post").then(res=>{
					if(res.succeed) {
						var obj = res.value;
						if(obj.msg){
							confirmModal(_that, '提示信息', obj.msg,()=>{
								if(obj.flag){
									_that.save()
								}
							},()=>{
								
							});
						}else if(obj.flag){
							_that.save()
						}
					}else{
						_that.om.toast(res.msg)
					}
				})
			}
		},
		save(){
			let _that = this;
			var arr = _that._.cloneDeep(_that.subEditorObj['title2'].workList)
			 for(var i=0;i<arr.length;i++){
				 var a = arr[i]
				 if(a.planStartTime){
					 a.planStartTime += ":00"
				 }
				 if(a.planEndTime){
					a.planEndTime += ":00"
				 }
				 if(a.startTime){
					 a.startTime += ":00"
				 }
				 if(a.endTime){
					a.endTime += ":00"
				 }
				 if(a.fileList == ''){
					 delete a.fileList
				 }
			 }
			 //子表提交数据赋值
			 _that.formdata.dataStr = JSON.stringify(arr)
			if(this.checkedit) {
				_that.om.formSave('commonForm/doCheckOrApproveUpdate', _that.formdata, _that)
			} else if(this.edit){
				_that.om.formSave('travelExpenses/doUpdate', _that.formdata, _that)
			} else {
				_that.om.formSave('travelExpenses/doAdd', _that.formdata, _that)
			}
		},
		getWorkParam() {
			let _that = this
			let formdata = _that.$refs.autoform.formdata
			return {
				checkedit:_that.checkedit,
				bxUserId:formdata.keyUserId,
				instId:formdata.keyInstId,
				instName:formdata.keyInstName,
				expenseCategoryId:formdata.expenseCategoryId,
				expenseCategoryName:formdata.expenseCategoryName,
				codeMap:JSON.stringify(this.codeMap),
				dvid:_that.dvid,
				erpProjectBatches:formdata.erpProjectBatches
			};
		},
		onSelectUser(id){
			let _that = this;
			//加载借款金额
			_that.om.request("loanList/getLoanSumByUserId", {
				userId: id
			}).then(res => {
				if (res.succeed) {
					var value = res.value;
					_that.$refs.autoform.formdata.loanAmount = value
					if(value > 0){
						_that.getListByCode()
						_that.$refs.autoform.changeEditor("title1","repaymentAmount","type",'numberbox') //实付金额
						_that.$refs.autoform.changeEditor("title1","repaymentAmount","prompt",'请输入') 
						_that.$refs.autoform.changeEditor("title1","payAmount","type",'numberbox') //实付金额
						_that.$refs.autoform.changeEditor("title1","payAmount","prompt",'请输入') 
						_that.$refs.autoform.changeEditor("title1","repaymentAmount","precision",'2')
						_that.$refs.autoform.changeEditor("title1","payAmount","precision",'2')
					}else{
						_that.$refs.autoform.changeEditor("title1","refundLoanCode","type",'labelbox')
					}
				} else {
					_that.$refs.autoform.formdata.loanAmount = ""
				}
			})
		},
		clearKeyUser(){
			var formdata  = this.$refs.autoform.formdata
			formdata.keyUserId = ""
			formdata.keyUserName = ""
			formdata.keyPostId = ""
			formdata.keyPostName = ""
			formdata.keyInstId = ""
			formdata.keyInstName = ""
		},
		onSelectKeyPostId(item) {
			let _that = this;
			_that.$refs.autoform.formdata.keyPostId = item.id
			_that.$refs.autoform.formdata.keyPostName = item.posname
			_that.$refs.autoform.formdata.keyInstId = item.instId
			_that.$refs.autoform.formdata.keyInstName = item.instName
		},
		clearKeyPostId(){
			let _that = this;
			_that.$refs.autoform.clear("title1","keyPostId")
			_that.$refs.autoform.clear("title1","keyInstId")
		},
		clearKeyUserId(){
			let _that = this;
			_that.$refs.autoform.clear("title1","keyUserId")
			_that.$refs.autoform.clear("title1","keyPostId")
			_that.$refs.autoform.clear("title1","keyInstId")
			_that.subEditorObj["title2"].workList = []
		},
		onSelectPayType(item) {
			let _that = this;
			_that.$refs.autoform.changeEditor("title1","bankUserId","required",false)
			_that.$refs.autoform.changeEditor("title1","payeeBankName","required",false)
			_that.$refs.autoform.changeEditor("title1","payeeBankAccount","required",false)
			_that.$refs.autoform.changeEditor("title1","bankUserId","type","linkbox")
			_that.$refs.autoform.changeEditor("title1","payeeBankName","type","textbox")
			_that.$refs.autoform.changeEditor("title1","payeeBankAccount","type","textbox")
			if(item.id == _that.codeMap.payeeBankDisabledId){
				_that.$refs.autoform.changeEditor("title1","bankUserId","type","labelbox")
				_that.$refs.autoform.changeEditor("title1","payeeBankName","type","labelbox")
				_that.$refs.autoform.changeEditor("title1","payeeBankAccount","type","labelbox")
				_that.$refs.autoform.clear("title1","bankUserId")
				_that.$refs.autoform.clear("title1","payeeBankName")
				_that.$refs.autoform.clear("title1","payeeBankAccount")
			}else if(item.id == _that.codeMap.payeeBankRequiredId){
				_that.$refs.autoform.changeEditor("title1","bankUserId","required",true)
				_that.$refs.autoform.changeEditor("title1","payeeBankName","required",true)
				_that.$refs.autoform.changeEditor("title1","payeeBankAccount","required",true)
				_that.getBankInfoFunc(_that.$refs.autoform.formdata.keyUserId)
			}
		},
		clearPayType(){
			let _that = this;
			_that.$refs.autoform.clear("title1","payTypeId")
			_that.$refs.autoform.changeEditor("title1","bankUserId","required",false)
			_that.$refs.autoform.changeEditor("title1","payeeBankName","required",false)
			_that.$refs.autoform.changeEditor("title1","payeeBankAccount","required",false)
		},
		initLoad(options) {
			let _that = this;
			var ajaxArr = [
				urlUtil.zposUrl(options.code),
				urlUtil.dictZeroComboboxUrl('37846'),
				{
					url:"travelExpenses/getCodeMap",
				},
				{
					url:'loanList/getLoanSumByUserId',
					param:{
						userId: _that.userId
					}
				},
				{
					url:"dictZero/getListByCode",
					param:{
						code:38400
					}
				},
				{
					url:'common/getMenu',
					param:{
						formCode:options.code
					},
				}
			];
			var fileId = options.fileId
			if(fileId){
				_that.dvid = fileId;
				ajaxArr.push({
					url:"travelExpenses/getValue",
					param:{fileId:fileId}
				})
			}
			formModelLoad(ajaxArr, function(res, mainData) {
				_that.menuList =  res[5].value
				if(res[3].value > 0){
					changeEditor("title1","refundLoanCode","type",'selectbox',mainData)
					changeEditor("title1","refundLoanCode","data",configSelectData(res[4],'code','dicname'),mainData)
					changeEditor("title1","refundLoanCode","onSelect",'onSelectRefundLoan',mainData)
					changeEditor("title1","repaymentAmount","type",'numberbox',mainData) //退款金额
					changeEditor("title1","repaymentAmount","prompt",'请输入',mainData)
					changeEditor("title1","payAmount","type",'numberbox',mainData) //实付金额
					changeEditor("title1","repaymentAmount",'precision','2',mainData) //退款金额
					changeEditor("title1","payAmount",'precision','2',mainData) //实付金额
					changeEditor("title1","payAmount","prompt",'请输入',mainData)
				}
				_that.codeMap = res[2].value;
				changeEditor("title1","sourceFormCode",'disabled',true,mainData)
				changeEditor("title1","sourceFormCode",'prompt','',mainData)
				changeEditor("title1","loanAmount",{
					defaultValue:res[3].value,
					defaultName:res[3].value
				},null,mainData)
				changeEditor("topinfo","zposId","data",configSelectData(res[0],'id','posname'),mainData)
				changeEditor("title1","keyPostId","data",configSelectData(res[0],'id','posname'),mainData)
				changeEditor('topinfo', 'zuserId', 'defaultValue', _that.userId, mainData);
				changeEditor('topinfo', 'zuserId', 'defaultName', _that.userName, mainData);
				changeEditor('title1', 'payTypeId', 'data', configSelectData(res[1], 'id', 'dicname'), mainData);
				changeEditor('title1', "keyUserId","link","../../public/pageSearch/pageSearch", mainData)
				changeEditor('title1', "keyUserId", "linkParam", {
					other: JSON.stringify({
						firstUserId: _that.userId
					}),
					namefield:"userPosInstName",
					searchfield:"q",
					initload:true,
					url:"temployee/getStaffCombogrid",
					cachename:_that.userCacheKey,
					placeholder:"请输入姓名或岗位"
				}, mainData)
				changeEditor("title1","currencyId",{
					link:'../../public/pageSearch/pageSearch',
					"linkParam":{
						namefield:'currencyCode',
						notefield:'currencyName',
						initload:true,
						searchfield:'q',
						pagination:true,
						cachename:_that.currencyIdCacheKey,
						url:'currencyDict/getCurrency',
						method:'get'
					}
				},null,mainData)
				changeEditor("title1","expenseCategoryId",{
					link:'../../public/pageSearch/pageSearch',
					"linkParam":{
						namefield:'typeName',
						notefield:'typeCode',
						initload:true,
						searchfield:'q',
						pagination:true,
						cachename:_that.expenseCategoryIdCacheKey,
						url:'expenseCategory/getExpenseCategoryPage',
						method:'get'
					}
				},null,mainData)
				changeEditor('title1', "bankUserId","link","../../public/pageSearch/pageSearch", mainData)
				changeEditor('title1', "bankUserId", "linkParam", {
					other: JSON.stringify({
						firstUserId: _that.userId
					}),
					namefield:"userPosInstName",
					searchfield:"q",
					initload:true,
					url:"temployee/getStaffCombogrid",
					cachename:_that.bankUserIdCacheKey,
					placeholder:"请输入姓名或岗位"
				}, mainData)
				changeEditor("title1","partakeInstId",{
					"link":'../../public/search/search',
					"linkParam":{
						other:JSON.stringify(),
						url:'tinstitution/getComboTree',
						namefield:'text',
						initload:true,
						cachename:_that.partakeInstCache
					}
				},null,mainData)
				changeEditor("title1","feesAggregatedWayIds",{
					"linkParam":{
						other:JSON.stringify({
							code:'40346'
						}),
						url:'tsysdict/getComboTree',
						namefield:'text',
						initload:true,
						cachename:_that.feesAggregatedWayCache
					}
				},null,mainData)
				changeEditor("title1","partakeUserId",{
					"link":'../../public/search/search',
					"linkParam":{
						other:JSON.stringify(),
						url:'orgInstPosUserOfficial/getUserListByInstPosId',
						namefield:'text',
						initload:true,
						cachename:_that.partakeUserCache
					}
				},null,mainData)
				changeEditor("title1","researchDevelopmentId",{
					"link":'../../public/pageSearch/pageSearch',
					"linkParam":{
						other:JSON.stringify({
							firstId:''
						}),
						url:'createProjectShow/findCreateProjectShowPage',
						namefield:"projectName",
						notefield:"projectCode",
						extrafield:"typeName",
						searchfield:'q',
						initload:true,
						cachename:_that.researchDevelopmentCache
					}
				},null,mainData)
				changeEditor("title1","businessOpportunityId",{
					"link":'../../public/pageSearch/pageSearch',
					"linkParam":{
						other:JSON.stringify({
							firstId:''
						}),
						url:'biddingProject/getBidding',
						namefield:'biddingProjectName',
						notefield:'biddingCode',
						searchfield:'q',
						initload:true,
						cachename:_that.businessOpportunityCache
					}
				},null,mainData)
				changeEditor("title1","saleOrderId",{
					"link":'../../public/pageSearch/pageSearch',
					"linkParam":{
						other:JSON.stringify({
							firstId:''
						}),
						url:'SaleOrderReviewShow/loadDataGrid',
						namefield:'customerNameX',
						notefield:'customerRequirementCode',
						searchfield:'q',
						initload:true,
						cachename:_that.saleOrderCache
					}
				},null,mainData)
				changeEditor("title1","marketingPlanningProductId",{
					"link":'../../public/search/search',
					"linkParam":{
						other:JSON.stringify({
							firstId:''
						}),
						url:'inventoryCategory/getExistingProductLineAssortment',
						namefield:'name',
						initload:true,
						cachename:_that.marketingPlanningProductCache
					}
				},null,mainData)
				
				changeEditor("title1","newProductId",{
					"link":'../../public/pageSearch/pageSearch',
					"linkParam":{
						other:JSON.stringify({
							firstId:'',
							likeFlag:false
						}),
						url:'productShowSecond/getProductPage',
						namefield:'newProductName',
						notefield:'newProductCode',
						initload:true,
						cachename:_that.newProductCache
					}
				},null,mainData)
				if(_that.subEditorObj["title2"]){
					changeEditor("title2", "dataStr", {
						getWorkParam: 'getWorkParam',
						titleTemplate:"<%= expenseTypeName || '无'%>",
						subtitle1Template:"<%= cityName  || '无'%>",
						subtitle2Template:"<%= remark || '无'%>"
					}, null, mainData)
				}
				//赋值
				if(fileId){
					var fieldArr = getFormFields(mainData)
					fieldArr.push("id")
					var dataList = _that._.cloneDeep(res[6].value.dataList)
					_that.subEditorObj["title2"].workList = dataList
					_that.$refs.autoform.$set(_that.$refs.autoform.formdata, "dataStr", JSON.stringify(dataList))
					_that.$set(_that.formdata, "dataStr", JSON.stringify(dataList))
					delete res[6].value.dataList
					for(var i in res[6].value){
						if(fieldArr.includes(i)){
							_that.$refs.autoform.$set(_that.$refs.autoform.formdata, i, res[6].value[i])
							_that.$set(_that.formdata, i, res[6].value[i])
						}
					}
					if(_that.$refs.autoform.formdata.loanAmount &&  Number(_that.$refs.autoform.formdata.loanAmount)> 0){
						changeEditor("title1","refundLoanCode","type",'selectbox',mainData)
						changeEditor("title1","refundLoanCode","data",configSelectData(res[4],'code','dicname'),mainData)
						changeEditor("title1","refundLoanCode","onSelect",'onSelectRefundLoan',mainData)
						changeEditor("title1","repaymentAmount","type",'numberbox',mainData) //退款金额
						changeEditor("title1","payAmount","type",'numberbox',mainData) //实付金额
						changeEditor("title1","repaymentAmount",'precision','2',mainData) //退款金额
						changeEditor("title1","payAmount",'precision','2',mainData) //实付金额
						changeEditor("title1","repaymentAmount","prompt",'请输入',mainData)
						changeEditor("title1","payAmount","prompt",'请输入',mainData)
					}else{
						changeEditor("title1","payAmount","type",'labelbox',mainData)
						changeEditor("title1","repaymentAmount","type",'labelbox',mainData)
					}
					if(_that.$refs.autoform.formdata.refundLoanCode == '38402'){
						changeEditor("title1","repaymentAmount","type",'numberbox',mainData)
						changeEditor("title1","repaymentAmount","required",true,mainData)
					}else{
						changeEditor("title1","repaymentAmount","type",'labelbox',mainData)
						changeEditor("title1","repaymentAmount","required",false,mainData)
					}
					if(_that.formdata.feesAggregatedWayIds){
						let idArr = _that.formdata.feesAggregatedWayIds.split(",")
						let nameArr = _that.formdata.feesAggregatedWayName.split(",")
						let feesAggregatedWayList = []
						for(let index in idArr){
							let obj = {
								id:idArr[index],
								text:nameArr[index]
							}
							feesAggregatedWayList.push(obj)
						}
						changeEditor('title1', 'feesAggregatedWayIds', {
							initSelect: feesAggregatedWayList
						},null,mainData)
					}
					if(_that.subEditorObj["title2"]){
						changeEditor("title2", "dataStr", {
							showDel: !_that.checkedit,
							showAdd:!_that.checkedit
						}, null, mainData)
					}
					//修改时初始化下拉框的值
					_that.$nextTick(function() {
						if(_that.$refs.autoform){
							_that.$refs.autoform.initSelectIndex("topinfo","zposId")
							_that.$refs.autoform.initSelectIndex("title1","keyPostId")
							_that.$refs.autoform.initSelectIndex('title1', 'payTypeId')
							_that.$refs.autoform.initSelectIndex('title1', 'refundLoanCode')
							if(_that.$refs.autoform.formdata.keyPostId){
								_that.om.request("orgInstPosUserOfficial/getPosComboboxByUser", {
									userId:_that.$refs.autoform.formdata.keyUserId
								}).then(res => {
									_that.$refs.autoform.changeEditor("title1","keyPostId","data",configSelectData(res,'id','posname'))
									_that.$refs.autoform.initSelectIndex("title1","keyPostId")
								})
							}
						}
					})
				}
				_that.$nextTick(function(){
					if(!_that.$refs.autoform.formdata.reimbursementDate){
						_that.$refs.autoform.formdata.reimbursementDate = moment().format('YYYY-MM-DD')
					}
					if(!_that.$refs.autoform.formdata.zposId){
						_that.$refs.autoform.formdata.zposId = res[0][0].id
						_that.$refs.autoform.formdata.zposName = res[0][0].posname
						_that.$refs.autoform.formdata.zinstId = res[0][0].instId
						_that.$refs.autoform.formdata.zinstName = res[0][0].instName
						_that.$refs.autoform.initSelectVal("topinfo","zposId")
					}
					if(!_that.$refs.autoform.formdata.keyUserId){
						_that.$refs.autoform.formdata.keyUserId = _that.userId
						_that.$refs.autoform.formdata.keyUserName = _that.userName
					}
					if(!_that.$refs.autoform.formdata.keyPostId){
						_that.$refs.autoform.formdata.keyPostId = res[0][0].id
						_that.$refs.autoform.formdata.keyPostName = res[0][0].posname
						_that.$refs.autoform.formdata.keyInstId = res[0][0].instId
						_that.$refs.autoform.formdata.keyInstName = res[0][0].instName
						_that.$nextTick(function(){
							_that.$refs.autoform.initSelectIndex("title1","keyPostId")
						})
					}
					if(!_that.$refs.autoform.formdata.bankUserId){
						_that.$refs.autoform.formdata.bankUserId = _that.userId
						_that.$refs.autoform.formdata.bankUserName = _that.userName
					}
					if(!_that.$refs.autoform.formdata.currencyId){
						_that.om.request("currencyDict/getLocalCurrency", {},'post').then(res => {
							_that.$refs.autoform.formdata.currencyId = res.value.id
							_that.$refs.autoform.formdata.currencyName = res.value.codeNameUnit
						})
					}
				})
			}, options)
			
		}
	},
	onLoad(options) {
		let _that = this;
		_that.formdata.userId = this.userId;
		_that.initLoad(options);
	},
	onUnload(){
		let _that = this
		//#ifdef APP-PLUS
			if (_that.$refs.autoform) {
				for (var fieldId in _that.subEditorObj) {
					uni.removeStorage({
						key: getWorkCacheKey(fieldId)
					});
				}
			}
		//#endif
		uni.removeStorage({
			key:_that.setDataCacheKey
		})
	},
	onShow() {
		let _that = this;
		if (_that.$refs.autoform) {
			for (var fieldId in _that.subEditorObj) {
				var editor = _that.subEditorObj[fieldId];
				uni.getStorage({
					key: getWorkCacheKey(fieldId),
					success: function(res) {
						editor.workList = res.data;
						_that.onSubChange(editor)
						uni.removeStorage({
							key: getWorkCacheKey(fieldId)
						});
					}
				});
			}
			uni.getStorage({
				key: _that.userCacheKey,
				success: function(res) {
					if(res.data){
						let d = res.data
						var formdata  = _that.$refs.autoform.formdata
						if(formdata.keyUserId != d.id){
							_that.subEditorObj["title2"].workList = []
						}
						
						formdata.keyUserId = d.id
						formdata.keyUserName = d.username
						formdata.keyPostId = d.salaryPosId
						formdata.keyPostName = d.salaryPosName
						formdata.keyInstId = d.salaryPosInstId
						formdata.keyInstName = d.salaryPosInstName
						formdata.reimbursementAmount = ''
						formdata.repaymentAmount = ''
						formdata.payAmount = ''
						_that.onSelectUser(d.id)
						_that.om.request("orgInstPosUserOfficial/getPosComboboxByUser", {
							userId: d.id
						}).then(res => {
							_that.$refs.autoform.changeEditor("title1","keyPostId","data",configSelectData(res,'id','posname'))
							_that.$refs.autoform.initSelectIndex("title1","keyPostId")
						})
						uni.removeStorage({
							key: _that.userCacheKey
						});
					}
				}
			});
			uni.getStorage({
				key:_that.currencyIdCacheKey,
				success:(res)=>{
					if(res.data){
						let d = res.data
						let formdata = _that.$refs.autoform.formdata
						formdata.currencyId = d.id
						formdata.currencyName = d.codeNameUnit
						uni.removeStorage({
							key:_that.currencyIdCacheKey
						})
					}
				} 
			})
			uni.getStorage({
				key:_that.expenseCategoryIdCacheKey,
				success:(res)=>{
					if(res.data){
						let d = res.data
						let formdata = _that.$refs.autoform.formdata
						formdata.expenseCategoryId = d.id
						formdata.expenseCategoryName = d.typeName
						uni.removeStorage({
							key:_that.expenseCategoryIdCacheKey
						})
					}
				} 
			})
			uni.getStorage({
				key: _that.bankUserIdCacheKey,
				success: function(res) {
					if(res.data){
						let d = res.data
						var formdata  = _that.$refs.autoform.formdata
						formdata.bankUserId = d.id
						formdata.bankUserName = d.username
						_that.getBankInfoFunc(d.id)
						uni.removeStorage({
							key: _that.bankUserIdCacheKey
						});
					}
				}
			});
			uni.getStorage({
				key: _that.partakeInstCache, //费用承担机构
				success: function(res) {
					if(res.data){
						let d = res.data
						var formdata  = _that.$refs.autoform.formdata
						formdata.partakeInstId = d.id
						formdata.partakeInstName = d.text
						_that.setData.partakeInstId = d.id
						_that.setData.partakeInstName = d.text
						_that.onSelectPartakeInst(d.id)
						uni.setStorage({
							key:_that.setDataCacheKey,
							data:_that.setData
						})
						if(_that.$refs.autoform.formdata.partakeUserId){
							_that.$refs.autoform.clear("title1","partakeUserId")
						}
						if(_that.subEditorObj['title2']){
							let dataList = _that.subEditorObj['title2'].workList
							for(let index in dataList){
								dataList[index].partakeInstId = d.id
								dataList[index].partakeInstName = d.text
							}
							formdata.dataStr = JSON.stringify(dataList)
							if(_that.subEditorObj['title2']){
								_that.subEditorObj['title2'].workList = dataList
							}
							_that.om.toast('子表数据已更新')
						}
						uni.removeStorage({
							key: _that.partakeInstCache
						});
					}
				}
			});
			uni.getStorage({
				key: _that.feesAggregatedWayCache, 
				success: function(res) {
					if(res.data){
						let d = res.data
						var formdata  = _that.$refs.autoform.formdata
						let ids =  d.map(e=> e.id).join(',')
						let names =  d.map(e=> e.text).join(',')
						formdata.feesAggregatedWayIds = ids
						formdata.feesAggregatedWayName = names
						_that.setData.feesAggregatedWayIds = ids
						_that.setData.feesAggregatedWayName = names
						_that.onSelectPartakeInst(d.id)
						uni.setStorage({
							key:_that.setDataCacheKey,
							data:_that.setData
						})
						_that.$refs.autoform.changeEditor('title1', 'feesAggregatedWayIds', {
							initSelect: d
						})
						if(_that.subEditorObj['title2']){
							let dataList = _that.subEditorObj['title2'].workList
							for(let index in dataList){
								dataList[index].feesAggregatedWayIds = ids
								dataList[index].feesAggregatedWayName = names
							}
							formdata.dataStr = JSON.stringify(dataList)
							if(_that.subEditorObj['title2']){
								_that.subEditorObj['title2'].workList = dataList
							}
							_that.om.toast('子表数据已更新')
						}
						uni.removeStorage({
							key: _that.feesAggregatedWayCache
						});
					}
				}
			});
			uni.getStorage({
				key:_that.partakeUserCache,
				success:(res)=>{
					if(res.data){
						let d = res.data
						let formdata = _that.$refs.autoform.formdata
						formdata.partakeUserId = d.id
						formdata.partakeUserName = d.username
					}
					uni.removeStorage({
						key:_that.partakeUserCache
					})
				}
			})
			uni.getStorage({
				key:_that.researchDevelopmentCache,
				success:(res)=>{
					if(res.data){
						let d = res.data
						let formdata = _that.$refs.autoform.formdata
						formdata.researchDevelopmentId = d.id
						formdata.researchDevelopmentName = d.projectName
						formdata.researchDevelopmentCode = d.projectCode
					}
					uni.removeStorage({
						key:_that.researchDevelopmentCache
					})
				}
			})
			uni.getStorage({
				key:_that.businessOpportunityCache,
				success:(res)=>{
					if(res.data){
						let d = res.data
						let formdata = _that.$refs.autoform.formdata
						formdata.businessOpportunityId = d.id
						formdata.businessOpportunityName = d.biddingProjectName
						formdata.businessOpportunityCode = d.biddingCode
					}
					uni.removeStorage({
						key:_that.businessOpportunityCache
					})
				}
			})
			uni.getStorage({
				key:_that.saleOrderCache,
				success:(res)=>{
					if(res.data){
						let d = res.data
						let formdata = _that.$refs.autoform.formdata
						formdata.saleOrderId = d.customerRequirementCode
						formdata.saleOrderCode = d.customerRequirementCode
					}
					uni.removeStorage({
						key:_that.saleOrderCache
					})
				}
			})
			uni.getStorage({
				key:_that.marketingPlanningProductCache,
				success:(res)=>{
					if(res.data){
						let d = res.data
						let formdata = _that.$refs.autoform.formdata
						formdata.marketingPlanningProductId = d.id
						formdata.marketingPlanningProductName = d.name
					}
					uni.removeStorage({
						key:_that.marketingPlanningProductCache
					})
				}
			})
			uni.getStorage({
				key:_that.newProductCache,
				success:(res)=>{
					if(res.data){
						let d = res.data
						let formdata = _that.$refs.autoform.formdata
						formdata.newProductId = d.id
						formdata.newProductCode = d.newProductCode
					}
					uni.removeStorage({
						key:_that.newProductCache
					})
				}
			})
			try {
				const value = uni.getStorageSync('chooseData');
				if (value) {
					let obj = {}
					let arr= []
					let name = ''
					let codes = []
					let sourceFormId = ''
					_that.$refs.autoform.formdata.keyUserId = value[0].infoId
					_that.$refs.autoform.formdata.keyUserName = value[0].infoName
					_that.$refs.autoform.formdata.keyInstId = value[0].rinstId
					_that.$refs.autoform.formdata.keyInstName = value[0].rinstName
					_that.$refs.autoform.formdata.keyPostId = value[0].salaryPosId
					_that.$refs.autoform.formdata.keyPostName = value[0].salaryPosName
					_that.$refs.autoform.formdata.partakeInstId = value[0].costInstId
					_that.$refs.autoform.formdata.partakeInstName= value[0].costInstName
					_that.onSelectPartakeInst(value[0].costInstId)
					_that.$refs.autoform.formdata.feesAggregatedWayIds= value[0].feesAggregatedWayCode
					_that.$refs.autoform.formdata.feesAggregatedWayName= value[0].feesAggregatedWayName
					_that.$refs.autoform.formdata.partakeUserId= value[0].partakeUserId
					_that.$refs.autoform.formdata.partakeUserName= value[0].partakeUserName
					_that.$refs.autoform.formdata.researchDevelopmentId= value[0].researchDevelopmentId
					_that.$refs.autoform.formdata.researchDevelopmentName= value[0].researchDevelopmentName
					_that.$refs.autoform.formdata.researchDevelopmentCode= value[0].researchDevelopmentCode
					_that.$refs.autoform.formdata.businessOpportunityId= value[0].businessOpportunityId
					_that.$refs.autoform.formdata.businessOpportunityName= value[0].businessOpportunityName
					_that.$refs.autoform.formdata.businessOpportunityCode= value[0].businessOpportunityCode
					_that.$refs.autoform.formdata.marketingPlanningProductId= value[0].marketingPlanningProductId
					_that.$refs.autoform.formdata.marketingPlanningProductName= value[0].marketingPlanningProductName
					_that.$refs.autoform.formdata.newProductId= value[0].newProductId
					_that.$refs.autoform.formdata.newProductCode= value[0].newProductCode
					_that.onSelectUser(value[0].infoId)
					_that.om.request("orgInstPosUserOfficial/getPosComboboxByUser", {
						userId: value[0].infoId
					}).then(res => {
						_that.$refs.autoform.changeEditor("title1","keyPostId","data",configSelectData(res,'id','posname'))
						_that.$refs.autoform.initSelectIndex("title1","keyPostId")
					})
					if(_that.subEditorObj["title2"]){
						let conifgData = _that.subConfigData["title2"]
						let fieldArr = getFormFields(conifgData)
						for(let index in fieldArr){
							_that.$set(obj,fieldArr[index],'')
						}
					}
					for(let item of value){
						let data = Object.assign({},obj)
						data.sourceFormId = item.id
						data.sourceForm = item.busName
						data.sourceFormCode = item.code
						name = item.busName
						sourceFormId = item.id 
						codes.push(item.code)
						for(let subItem of item.subData){
							data.planStartTime = subItem.startTime
							data.planEndTime = subItem.endTime
							data.cityId = subItem.addressId
							data.cityName = subItem.addressName
							data.address = subItem.street
							data.remark = subItem.reason
							data.vehicleTypeCode = subItem.vehicleCode
							data.vehicleTypeName = subItem.vehicleName
							data.sameOutUserId = subItem.sameOutUserId
							data.sameOutUserName = subItem.sameOutUserName
							data.proportion = subItem.proportion
							data.partakeInstId  = subItem.partakeInstId
							data.partakeInstName = subItem.partakeInstName
							data.feesAggregatedWayIds = subItem.feesAggregatedWayCode
							data.feesAggregatedWayName = subItem.feesAggregatedWayName
							data.partakeUserId = subItem.partakeUserId
							data.partakeUserName = subItem.partakeUserName
							data.researchDevelopmentId = subItem.researchDevelopmentId
							data.researchDevelopmentName = subItem.researchDevelopmentName
							data.researchDevelopmentCode = subItem.researchDevelopmentCode
							data.businessOpportunityId = subItem.businessOpportunityId
							data.businessOpportunityName = subItem.businessOpportunityName
							data.businessOpportunityCode = subItem.businessOpportunityCode
							data.marketingPlanningProductId = subItem.marketingPlanningProductId
							data.marketingPlanningProductName = subItem.marketingPlanningProductName
							data.newProductId = subItem.newProductId
							data.newProductCode = subItem.newProductCode
							data.sourceFormBusId = subItem.sourceFormBusId
							data.sourceFormBusCode = subItem.sourceFormBusCode
							data.sourceSubFormId = subItem.sourceSubFormId
							if(subItem.checked){
								arr.push(data)
							}
						}
					}
					_that.$refs.autoform.formdata.sourceFormCode = codes.map(e=> e).join(',')
					_that.$refs.autoform.formdata.sourceForm = name
					_that.$refs.autoform.formdata.sourceFormId = sourceFormId
					if(_that.subEditorObj["title2"]){
						_that.subEditorObj["title2"].workList = arr
					}
					uni.removeStorageSync('chooseData')
				}
			} catch (e) {
				// error
			}
			
		}
	}
};
</script>
<style></style>